package com.liao.badminton.exception;

import com.liao.badminton.code.RespCodeMessage;
import com.liao.badminton.code.ResponseRest;
import com.liao.badminton.code.util.ResponseUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.AuthorizationServiceException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.csrf.CsrfException;
import org.springframework.security.web.csrf.InvalidCsrfTokenException;
import org.springframework.security.web.csrf.MissingCsrfTokenException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * author liaocheng
 * description : 鉴权异常
 * DATE: 2021/2/22
 */
@Component
public class MyAuthorException implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, AccessDeniedException e) {
        String requestURI = httpServletRequest.getRequestURI();
        ResponseRest result = null;
        if (e instanceof AuthorizationServiceException || e instanceof AccessDeniedException) {
            result = ResponseRest.fail(requestURI, RespCodeMessage.SECURITY_ACCOUNT_UN_AUTHOR, e.getMessage());
        } else if (e instanceof CsrfException) {
            result = ResponseRest.fail(requestURI, "csr异常");
        } else if (e instanceof InvalidCsrfTokenException) {
            result = ResponseRest.fail(requestURI, "csr异常");
        } else if (e instanceof MissingCsrfTokenException) {
            result = ResponseRest.fail(requestURI, "csr异常");
        } else {
            result = ResponseRest.fail(requestURI).setMsg(e.getMessage());
        }
        ResponseUtils.out(response, result);
    }
}
